<template>
  <div style="display:flex;flex-direction: column" class="h100">
     <a-form-model
          ref="ruleForm"
           :model="dataSource[dataAdress].queryParam"
           :rules="rules"
           class="AsteriskAfter newEditStyle rightDrawerWithoutCol">
    <!-- 有效期 -->
              <a-form-model-item v-if="showFileOnly" :label="$t('expirationDate')" :required="true" >
                <a-form-model-item
                  prop="startTime"
                  :style="{ display: 'inline-block', width: 'calc(50% - 12px)', marginBottom: 0 }"
                >
                  <a-date-picker
                    :showTime="{ format: 'HH:mm' }"
                    format="YYYY-MM-DD HH:mm"
                    :disabledDate="disabledStartDate"
                    :disabledTime="disabledEndTime"
                    @openChange="handleStartOpenChange"
                    style="width: 100%"
                    v-model="dataSource[dataAdress].queryParam.startTime"
                  />
                </a-form-model-item>
                <span :style="{ display: 'inline-block', width: '24px', textAlign: 'center' }">-</span>
                <a-form-model-item
                  prop="endTime"
                  :style="{ display: 'inline-block', width: 'calc(50% - 12px)', marginBottom: 0 }"
                >
                  <a-date-picker
                    :showTime="{ format: 'HH:mm' }"
                    format="YYYY-MM-DD HH:mm"
                    :disabledDate="disabledEndDate"
                    :open="endOpen"
                    @openChange="handleEndOpenChange"
                    style="width: 100%"
                    v-model="dataSource[dataAdress].queryParam.endTime"
                  />
                </a-form-model-item>
              </a-form-model-item>
    <a-radio-group style="padding-bottom: 24px" name="radioGroup" v-model="dataSource[dataAdress].choseType">
      <a-radio v-if="!showFileOnly" :value="1">
        {{ $t('multiSelect') }}
      </a-radio>
      <a-radio :value="2">
        {{ $t('fileImport') }}
      </a-radio>
    </a-radio-group>
    <!-- 批量选择 -->
    <view-chose-car-list :dataAdress="dataAdress" v-if="dataSource[dataAdress].choseType===1"></view-chose-car-list>
    <!-- 来自文件 -->
    <div v-else>
      <a-form-model-item prop="fileName">
        <a-input
          class="formFileInput"
          :placeholder="$t('formatFiles')"
          readOnly
          :value="dataSource[dataAdress].queryParam.fileName"
        >
          <template #addonAfter>
            <i class="iconfont icon-shangchuan" @click="upload"></i>
          </template>
        </a-input>
        <!-- 下载模板 -->
      <a-button
        @click="downloadFile"
        :loading="downloading"
        style="vertical-align: text-bottom;"
      >{{ $t('downloadTemplate') }}
      </a-button>
      </a-form-model-item>
      <div v-if="uploadRes.total!=0">
        <p style="line-height:30px">
          <span>文件车辆数：{{ uploadRes.total||'-' }}</span>
          <span style="margin-left:20px">导入车辆数：</span><span style="color: green">{{ uploadRes.success ||'-' }}</span>
          <span style="margin-left:20px">失败车辆数：</span><span style="color: red">{{ uploadRes.fail||'-' }}</span>
          &nbsp;&nbsp;<a-button @click="downloadImportResultFile" v-if="uploadRes.detailExcelUrl">{{$t("exportResult")}}</a-button>
        </p>
      </div>
      <div v-if="uploadRes.total==0">
        <a-empty style="margin-top:77px">
          <span slot="description">导入车辆文件内容为空!</span>
        </a-empty>
      </div>
      <!-- 来自文件上传 -->
      <local-upload
        ref="upload"
        :domView="false"
        @showFileObj="showFileObj"
        :accept="['.xls','.xlsx']"
      ></local-upload>
      <!-- 任务审核(流程图及节点审批用户设置)-->
        <div v-if="showFileOnly && dataSource[dataAdress].enableAddCarAudit">
          <a-form-model-item label="追加车辆审核" ></a-form-model-item>
          <!-- 流程图 -->
          <div style="height:360px;margin-bottom:16px">
            <process-viewer
              :key="`designer-${processView.index}`"
              v-if="processView.index"
              :xml="processView.xmlData"
              style="height:100%" />
          </div>
          <!-- 节点信息 -->
          <audit-flow-process ref="auditProcessRef" method-name="getAddCarFlowDesinNodeData"></audit-flow-process>
        </div>
    </div>
    </a-form-model>
  </div>
</template>
<script>
import moment from 'moment'
import ListDetailLayout from '@/views/components/ListDetailLayout'
import ViewChoseCarList from './ViewChoseCarList'
import { mapState } from 'vuex'
import { downloadBlobFile } from '@/utils/functions'
import LocalUpload from '@/components/Upload/LocalUpload'
import AuditFlowProcess from '@/views/components/AuditFlowProcess/config.vue'
import ProcessViewer from '@/components/ProcessViewer'
import flowDesignApi from '@/api/modules/flowManage/flowDesign'
const initProcessView = {
  index: '',
  xmlData: ''
}

export default {
  name: 'NewTaskStep2',
  components: {
    ListDetailLayout,
    ViewChoseCarList,
    LocalUpload,
    AuditFlowProcess,
    ProcessViewer
  },
  props: {
    dataAdress: {
      type: String,
      default: 'detailAddCar'
    },
   showFileOnly: {
     type: Boolean,
     default: false
   }
  },
  computed: {
    ...mapState({
      dataSource: (state) => state.newTask,

    })
  },
  created() {
    console.log(this.dataAdress)
    console.log(this.dataSource[this.dataAdress])
    this.getProcessXmlData()
  },
  data () {
    return {
      endOpen: false,
      downloading: false,
      uploadRes: {
        fail: null,
        success: null,
        total: null
      },
      processView: {
        ...initProcessView
      },
      loadingProcess: false,
      rules: {
        startTime: [{ required: true, validator: this.startTimeValidator }],
        endTime: [{ required: true, validator: this.endTimeValidator }],
        fileName: [{ required: true, message: this.$t("pleaseUpload") }]
      },
      form:{
        startTime: undefined,
        endTime:undefined
      }
    }
  },
  methods: {
    //   上传文件
    upload () {
      this.$refs.upload.uploadDo()
    },
    // 回显上传文件
    showFileObj (value) {

      const vm = this
      vm.dataSource[vm.dataAdress].file = value
      vm.dataSource[vm.dataAdress].queryParam.fileName = value.name
      vm.$refs.ruleForm.clearValidate('fileName')

      const formData = new FormData()
      formData.append('file', value)
      formData.append('strategyId', vm.dataSource[vm.dataAdress].strategyId)
      if(vm.dataSource[vm.dataAdress].taskId){
        formData.append('taskId', vm.dataSource[vm.dataAdress].taskId)
      }


      vm.dataSource[vm.dataAdress].pretreatmentId = null
      vm.$api.fliePretreatment(formData).then(res => {
        if (res.data && res.data.pretreatmentId) {
          vm.dataSource[vm.dataAdress].pretreatmentId = res.data.pretreatmentId
          vm.dataSource[vm.dataAdress].fileFailCar = res.data.failNumber + res.data.repeatNumber
          vm.dataSource[vm.dataAdress].fileSuccessCar = res.data.successNumber
          vm.dataSource[vm.dataAdress].fileTotal = res.data.failNumber + res.data.repeatNumber + res.data.successNumber

          this.uploadRes = Object.assign(this.uploadRes, res.data);
          this.uploadRes.fail = res.data.failNumber + res.data.repeatNumber
          this.uploadRes.success = res.data.successNumber
          this.uploadRes.total = res.data.failNumber + res.data.repeatNumber + res.data.successNumber
        }
      }).catch(() => {
        vm.dataSource[vm.dataAdress].file = {}
        vm.dataSource[vm.dataAdress].queryParam.fileName = ''
        vm.$refs.ruleForm.validateField('fileName')
      })
    },
    // 下载模板
    downloadFile () {
      this.$api.downloadTaskCarTpl().then((res) => {
        downloadBlobFile(res, `${this.$t('downloadTemplate')}.xlsx`)
      }).finally(() => {
        this.downloading = false
      })
    },
    downloadImportResultFile () {
      if (!this.uploadRes.detailExcelUrl) {
        return ;
      }
      if (this.uploadRes.detailExcelUrl.indexOf("http") === 0) {
        window.open(this.uploadRes.detailExcelUrl);
        return ;
      }
      return this.axios({
        url: this.uploadRes.detailExcelUrl,
        method: 'post',
        responseType: 'blob'
      }).then((res) => {
        downloadBlobFile(res, "下载结果.xlsx")
      });
    },
    // 提交验证
    getFormValid () {
        this.$refs.ruleForm.validate(valid => {
          if (!valid) {
             return false
          }
          return true
        })
    },
    handleStartOpenChange (open) {
      if (!open) {
        this.endOpen = true
      }
    },
    handleEndOpenChange (open) {
      this.endOpen = open
    },
    /// ////时间验证
        startTimeValidator (rule, value, callback) {
          const vm = this
          const errors = []
          if (rule.required) {
            !value && errors.push(new Error(vm.$t('pleaseSelect')))
          }
          if((value.format("h[h] m[m]")!=moment(new Date()).format("h[h] m[m]")) && value.isBefore(new Date())){
            errors.push(new Error(vm.$t('时间不能早于当前时间')))
          }
          callback(errors[0])
        },
        endTimeValidator (rule, value, callback) {
          const vm = this
          const startValue = this.dataSource[this.dataAdress].queryParam.startTime
          const errors = []
          if (rule.required) {
            !value && errors.push(new Error(vm.$t('pleaseSelect')))
          }
          if (value && value < moment(moment().format('YYYY-MM-DD'))) {
            // 结束日期不能小于当前日期
            errors.push(new Error(vm.$t('newTaskTimeTip1')))
          }
          if (startValue) {
            if (value && startValue && value.valueOf() - (24 * 60 * 60 * 1000) < startValue.valueOf()) {
              // 开始与结束时间至少相差24小时
              errors.push(new Error(vm.$t('newTaskTimeTip2')))
            }
          }
          callback(errors[0])
        },
        disabledStartDate (startValue) {
            const endValue = this.dataSource[this.dataAdress].queryParam.endTime
            if (!startValue || !endValue) {
              return startValue < moment(moment().format('YYYY-MM-DD')) // 不能用HH:mm:ss 因为当前日期不能选 体验就不好
            }
            return startValue < moment(moment().format('YYYY-MM-DD')) || startValue.valueOf() > endValue.valueOf()
        },
        disabledEndDate (endValue) {
          const startValue = this.dataSource[this.dataAdress].queryParam.startTime
          if (!endValue || !startValue) {
            return endValue < moment(moment().format('YYYY-MM-DD'))
          }
          return startValue.valueOf() >= endValue.valueOf() || endValue < moment(moment().format('YYYY-MM-DD'))
        },
        range(start, end){
          const result = [];
          for (let i = start; i < end; i++) {
              result.push(i);
          }
          return result;
        },
        disabledEndTime(date){
          let currentDay = moment().date();    //当下的时间
          let currentHours = moment().hours();
          let currentMinutes = moment().minutes();  //设置的时间
          let settingHours = moment(date).hours();
          let settingDay = moment(date).date();
          if (date && settingDay === currentDay && settingHours === currentHours) {
              return {       
                  disabledHours: () => this.range(0, currentHours),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
                  disabledMinutes: () => this.range(0, currentMinutes),
              };
          }else if (date && settingDay === currentDay && settingHours > currentHours) {
              return { 
                  disabledHours: () => this.range(0, currentHours),      //设置为当天现在这小时之后，只禁用当天该小时之前的时间 
              };   
          }else if (date && settingDay === currentDay && settingHours < currentHours) {
              return {
                  disabledHours: () => this.range(0, currentHours),      //若先设置了的小时小于当前的，再设置日期为当天，需要禁用当天现在这小时之前的时间和所有的分
                  disabledMinutes: () => this.range(0, 59),
              }
          }else if (date && settingDay > currentDay) {
              return {                                    
                  disabledHours: () => [],                     //设置为当天之后的日期，则不应有任何时间分钟的限制
                  disabledMinutes: () => [],
              }
          }else{
            return {       
              disabledHours: () => this.range(0, currentHours),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
              disabledMinutes: () => this.range(0, currentMinutes),
            };
          }
        },
        // 获取流程图
        getProcessXmlData () {
          this.loadingProcess = true
          flowDesignApi.getAddCarFlowDesinXmlData().then(res => {
            this.processView.index = 'process' + Math.random
            this.processView.xmlData = res.data
          }).finally(() => {
            this.loadingProcess = false
          }).catch(err => {
            console.log(err)
          })
        }

    }
}
</script>
<style lang="less" scoped>
  // 来自文件时，上传和按钮位置
  .formFileInput {
    width: calc(100% - 120px);
    margin-bottom: 18px;

    & ~ .ant-btn {
      width: 108px;
      padding: 0;
      margin-left:10px;
    }
  }

</style>
